package com.yurun.organizationmodule.service.Impl;

import com.github.pagehelper.PageInfo;
import com.yurun.commonapi.api.CommonResult;
import com.yurun.commonapi.pojo.Employee;
import com.yurun.commonapi.pojo.OrganizationInfo;
import com.yurun.commonapi.pojo.UmsRole;
import com.yurun.employeemodule.mapper.EmployeeMapper;
import com.yurun.organizationmodule.mapper.OrganizationMapper;
import com.yurun.organizationmodule.service.OrganizationService;
import com.yurun.orgpermissionmodule.mapper.OrgPermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.DigestUtils;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
@Transactional
public class OrganzationServiceImpl implements OrganizationService {

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private OrgPermissionMapper permissionModuleMapper;


    @Override
    public List<OrganizationInfo> getAllOrganizationList() {
        return organizationMapper.getAllOrganizationList();
    }

    @Override
    public List<String> getOrgOption() {
        return organizationMapper.getOrgOption();
    }

    @Override
    public boolean addOrg(OrganizationInfo organizationInfo) {

        organizationInfo.setCreateTime(new Date());
        organizationInfo.setUpdateTime(new Date());
        organizationInfo.setIsDel(0);
        organizationInfo.setStatus(1);  // 机构审核通过


        Employee employee = new Employee();
        // 生成员工id
        BigInteger employeeId = getEnumId(organizationInfo.getAreaCode());
        Integer flag_employeeId = employeeMapper.verifyEmployeeIdIsRepeat(employeeId);
        // 判断是否已存在该员工id
        while (flag_employeeId != null) {  // 已存在
            employeeId = getEnumId(organizationInfo.getAreaCode());
            flag_employeeId = employeeMapper.verifyEmployeeIdIsRepeat(employeeId);
        }

        BigInteger organizationId = getOrgId(organizationInfo.getAreaCode());
        BigInteger flag_organizationId = organizationMapper.orgIdIsRepeat(organizationId);

        // 判断是否已存在该机构id
        while (flag_organizationId != null) {  // 已存在
            organizationId = getOrgId(organizationInfo.getAreaCode());
            flag_organizationId = organizationMapper.orgIdIsRepeat(organizationId);
        }

        organizationInfo.setOrganizationId(organizationId);


        employee.setEmployeeId(employeeId);
        employee.setOrganizationId(organizationId);
        employee.setEmployeePwd(setMD5PWD("123456"));
        employee.setEmployeeName("机构经理");
        employee.setBranchId(BigInteger.valueOf(0));
        employee.setEmployeeAddress(organizationInfo.getOrganizationAddress());
        employee.setEmployeeArea(organizationInfo.getOrganizationArea());
        employee.setEmployeeCity(organizationInfo.getOrganizationCity());
        employee.setEmployeePlace(organizationInfo.getOrganizationPlace());
        employee.setEmployeeIcon(organizationInfo.getOrganizationLogo());
        employee.setEmployeeIdcard(organizationInfo.getPrincipalIdCard());
        employee.setEmployeeIdcardNumber(organizationInfo.getPrincipalIdcardNumber());
        employee.setEmployeePhone(organizationInfo.getPrincipalPhone());
        employee.setEmployeePosition("10");
        employee.setEmployeeProvince(organizationInfo.getOrganizationProvince());
        employee.setEmployeeSex(0);
        employee.setIsDel(0);
        employee.setStatus(1);
        employee.setCreateTime(new Date());
        employee.setUpdateTime(new Date());

        try {
            //permissionModuleMapper.addRole(role); // 增加机构管理员角色
            int roleAdmin = addRole(organizationId, "机构经理");
            int roleBranchAdmin = addRole(organizationId, "分店经理");
            int roleTeacher = addRole(organizationId, "普通教师");
            int roleTeacherManage = addRole(organizationId, "教学负责人");
            int roleTeacherTeam = addRole(organizationId, "教学组长");
            int roleZR = addRole(organizationId, "主任");
            int roleRS = addRole(organizationId, "人事");
            int roleZL = addRole(organizationId, "助理");
            //int roleId = role.getId();//permissionModuleMapper.getRoleIdByOrgId(role.getOrganizationId()); // 获取roleId

            // 给员工增加角色
            permissionModuleMapper.addEmployeeRole(roleAdmin, employeeId);
            // 获取所有菜单id
            //List<Integer> array = menuMapper.getAllMenuId();

            /**
             * 添加菜单操作是按照数据库中存储的默认角色对应的菜单
             */
            // 增加机构超级管理员菜单,默认添加数据库中roleId为9的菜单
            addMenu(roleAdmin, organizationMapper.getMenuListByRole(9));
            // 增加教师菜单
            addMenu(roleTeacher, organizationMapper.getMenuListByRole(1));
            // 增加教学负责人菜单
            addMenu(roleTeacherManage, organizationMapper.getMenuListByRole(2));
            // 增加教学组长菜单
            addMenu(roleTeacherTeam, organizationMapper.getMenuListByRole(4));
            // 增加主任菜单
            addMenu(roleZR, organizationMapper.getMenuListByRole(3));
            // 增加人事菜单
            addMenu(roleRS, organizationMapper.getMenuListByRole(5));
            // 增加行政助理菜单
            addMenu(roleZL, organizationMapper.getMenuListByRole(3));
            // 增加分店经理菜单
            addMenu(roleBranchAdmin, organizationMapper.getMenuListByRole(10));
            /**
             * 添加权限是按照数据库中存储的权限类别字段（category_id）进行区分并添加的
             * 0表示常见权限，1表示机构经理，2表示分店经理， 3表示其他权限
             * 10表示普通教师
             * 11表示教学负责人
             * 12表示教研组长
             * 13表示人事
             */
            //int[] arr_admin = {0, 1, 11,13};
            List<Integer>  arr_teacher = organizationMapper.getPermissionByRole(1); // 普通教师
            List<Integer>  arr_teacherTeam = organizationMapper.getPermissionByRole(2); // 教研组长
            List<Integer>  arr_admin = organizationMapper.getPermissionByRole(3); // 机构经理
            List<Integer>  arr_branchAdmin = organizationMapper.getPermissionByRole(4); // 分店经理
            List<Integer>  arr_RS = organizationMapper.getPermissionByRole(5); // 人事
            List<Integer>  arr_ZR= organizationMapper.getPermissionByRole(6); // 主任
            List<Integer>  arr_teacherManage = organizationMapper.getPermissionByRole(7); // 教学负责人
            List<Integer>  arr_ZL = organizationMapper.getPermissionByRole(8); // 助理
            //int[] arr_teacherTeam = {12};
            //int[] arr_RS = {13};
            addPermission(roleAdmin, arr_admin); // 增加机构经理权限
            addPermission(roleTeacher, arr_teacher); // 增加教师权限
            addPermission(roleTeacherManage, arr_teacherManage); // 增加教学负责人权限
            addPermission(roleRS, arr_RS); // 增加人事权限
            addPermission(roleTeacherTeam, arr_teacherTeam); // 增加教学组长权限
            addPermission(roleZR, arr_ZR); // 增加主任权限
            addPermission(roleZL, arr_ZL); // 增加助理权限
            addPermission(roleBranchAdmin, arr_branchAdmin); // 增加分店经理权限
            //addPermission(roleTeacherTeam, arr_teacherTeam);
            //int[] arr_teacherTeam = {1010,1007,1003,1018,1013,1014,1017,1031,1032,1038,1039,1040,1041,1042,1044,1045, 1073,1074}; // 增加教研组长的权限



            // 增加机构
            organizationMapper.addOrg(organizationInfo);
            // 增加员工
            employeeMapper.addEmployee(employee);

            return true;

        } catch (Exception e) {
            System.out.println("发生异常,进行手动回滚！");
            // 手动回滚事物
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return  false;
    }

    @Override
    public List<OrganizationInfo> getOneOrgInfoByName(String organizationName) {
        return organizationMapper.getOneOrgInfoByName(organizationName);
    }

    @Override
    public List<OrganizationInfo> getOrganizationList(String keyword) {
        if (!keyword.equals("") && keyword != null){
            return organizationMapper.getOneOrgInfoByName(keyword);
        }
        return organizationMapper.getAllOrganizationList();
    }

    @Override
    public OrganizationInfo getOneOrgInfoById(BigInteger organizationId) {
        return organizationMapper.getOneOrgInfoById(organizationId);
    }

    @Override
    public boolean editOrgById(OrganizationInfo organizationInfo) {
        organizationInfo.setUpdateTime(new Date());
        return organizationMapper.editOrgById(organizationInfo) == 1;
    }

    @Override
    public boolean delOrgById(BigInteger organizationId) {
        Date time = new Date();
        try {
            organizationMapper.delBranchByOrgId(organizationId, time);
            organizationMapper.delOrgById(organizationId, time);
            organizationMapper.delEmployeeByOrgId(organizationId, time);
            organizationMapper.delTeacherByOrgId(organizationId, time);
            organizationMapper.delStudentByOrgId(organizationId, time);
            return true;
        } catch (Exception e) {
            System.out.println("发生异常,进行手动回滚！");
            // 手动回滚事物
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public CommonResult getAdminEmployeeId(BigInteger organizationId) {
        return CommonResult.success(organizationMapper.getAdminEmployeeId(organizationId).get(0));
    }

    public BigInteger getEnumId(String placeNum) {
        Random random = new Random();
        StringBuilder result= new StringBuilder();
        for (int i=0;i<6;i++)
        {
            result.append(random.nextInt(10));
        }
        return BigInteger.valueOf(Long.parseLong(placeNum + result));
    }

    public BigInteger getOrgId(String placeNum) {
        Random random = new Random();
        StringBuilder result= new StringBuilder();
        for (int i=0;i<4;i++)
        {
            result.append(random.nextInt(10));
        }
        return BigInteger.valueOf(Long.parseLong(placeNum + result));
    }

    public int addRole(BigInteger organizationId, String roleName) {
        // 新增角色
        UmsRole role = new UmsRole();
        role.setOrganizationId(organizationId);
        role.setStatus(1);
        role.setDescription(roleName);
        role.setName(roleName);
        role.setCreateTime(new Date());
        role.setUpdateTime(new Date());
        permissionModuleMapper.addRole(role); // 增加角色

        return role.getId();
    }

    public void addMenu(int roleId, List<Integer> array) {
        for (int i = 0; i < array.size(); i++) {
            // 增加菜单
            permissionModuleMapper.addMenuByRoleId(roleId, array.get(i));
        }
    }

    public void addPermission(int roleId, int[] arr) {
        // 增加权限
        for (int value : arr) {
            for (int list : organizationMapper.getAdminAllPermission(value)) {
                permissionModuleMapper.addPermissionByRoleId(roleId, list);
            }
        }
    }

    public void addPermission(int roleId, List<Integer> arr) {
        // 增加权限
        for (int value : arr) {
            permissionModuleMapper.addPermissionByRoleId(roleId, value);
        }
    }


    public String setMD5PWD(String password){
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }
}
